package com.atguigu.flink04;

import com.atguigu.beans.WaterSensor;
import com.atguigu.func.WaterSensorMapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

/**
 * @author Felix
 * @date 2024/2/22
 * 该案例演示了使用侧输出流实现分流操作
 * 需求：将WaterSensor按照Id类型进行分流
 *      如果id=='s1' ---- 放到ds1流
 *      如果id=='s2' ---- 放到ds2流
 *      其它 ---- 放到主流
 */
public class Flink04_SplitStream_Output {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        //StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> wsDS = env
                .socketTextStream("hadoop102", 8888)
                .map(new WaterSensorMapFunction());

        //创建侧输出流标签
        // 注意：侧输出流标签底层是单例的，一个id对应的是同一个对象
        // 在创建对象的时候，底层会对泛型进行擦除，应该以匿名内部类的方式创建对象 或者在构造方法中传递参数
        OutputTag<String> s1Tag = new OutputTag<String>("s1Tag"){};
        OutputTag<String> s2Tag = new OutputTag<String>("s2Tag", Types.STRING);

        //要向将主流的数据放到侧输出流中，必须要用到上下文对象，需要通过process对流中数据进行处理
        SingleOutputStreamOperator<String> splitDS = wsDS.process(
                new ProcessFunction<WaterSensor, String>() {
                    @Override
                    public void processElement(WaterSensor ws, ProcessFunction<WaterSensor, String>.Context ctx, Collector<String> out) throws Exception {
                        String id = ws.id;
                        if ("s1".equals(id)) {
                            //将数据放到s1侧输出流
                            ctx.output(s1Tag, ws.toString());
                        } else if ("s2".equals(id)) {
                            //将数据放到s2侧输出流
                            ctx.output(s2Tag, ws.toString());
                        } else {
                            //将数据放到主流
                            out.collect(ws.toString());
                        }
                    }
                }
        );

        //通过主流获取侧输出流数据
        SideOutputDataStream<String> ds1 = splitDS.getSideOutput(s1Tag);
        SideOutputDataStream<String> ds2 = splitDS.getSideOutput(s2Tag);

        splitDS.print("主流：");
        ds1.print("ds1：");
        ds2.print("ds2：");

        env.execute();
    }
}
